import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
import authMenuList from "@/assets/json/authMenuList.json";
import piniaPersistConfig from "../helper/persist";

export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: {},
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: "",
    currentJobList: [],
    currentJobId: undefined,
    currentJobName: "",

  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getAuthButtonListApi();
      this.authButtonList = data;
    },
    // 设置职位列表
    setCurrentJobList(currentJobList: AuthState["currentJobList"]) {
      this.currentJobList = currentJobList;
    },
    //设置职位当前职位id
    setCurrentJobId(currentJobId: AuthState["currentJobId"]) {
      this.currentJobId = currentJobId;
    },
    //设置职位当前职位名称
    setCurrentJobName(currentJobName: AuthState["currentJobName"]) {
      this.currentJobName = currentJobName;
    },
    // 转换菜单信息，menuList完整的菜单信息，userMenuList用户的权限菜单信息
    convertMenuInformation(menuList: any[], userMenuList: any[]) {
      const menuMap = new Map();
      // // 递归函数，用于将菜单转换为 Map
      const convertToMap = (menu) => {
        if (menu.meta && menu.meta.title) {
          menuMap.set(menu.meta.title, menu);
        }

        if (menu.children) {
          menu.children.forEach(child => {
            convertToMap(child);
          });
        }
      };

      // 将 menuList 转换为 Map，方便查找
      menuList.forEach(menu => {
        convertToMap(menu);
      });

      // 递归函数，用于构建菜单树
      const buildMenuTree = (menu: any) => {
        // console.log('menu', menu, menuMap.get(menu.menuName));

        const menuItem: any = {
          path: menu.url,
          name: menu.cacheCode,
          // component: menu.url,
          component: menuMap.get(menu.menuName).component,
          meta: {
            icon: menu.icon || "Menu",
            title: menu.menuName,
            isLink: "",
            isHide: menu.visible == '0' ? false : true,
            isFull: false,
            isAffix: menuMap.get(menu.menuName)?.meta?.isAffix || false,
            // activeMenu: menuMap.get(menu.menuName)?.meta?.activeMenu || "",
            isKeepAlive: menu.cache == '0' ? false : true
          },
          children: []
        };


        // 检查 menuList 中的 redirect 属性
        const menuInList = menuMap.get(menu.menuName);
        if (menuInList && menuInList.redirect) {
          menuItem.redirect = menuInList.redirect
        }

        // 检查 menuList 中的 activeMenu 属性
        if (menuInList && menuInList.meta && menuInList.meta.activeMenu) {
          menuItem.meta.activeMenu = menuInList.meta.activeMenu;
        }

        if (menu.children) {
          menu.children.forEach(item => {
            if (item.menuType !== 'F') {
              menuItem.children.push(buildMenuTree(item));
            }
          });
        }

        return menuItem;
      }

      // 构建根菜单数组
      const rootMenuArray: any[] = [];

      userMenuList.forEach(menu => {
        rootMenuArray.push(buildMenuTree(menu));
      });

      return rootMenuArray;
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const params = {
        id: this.currentJobId
      };
      const { menuDtoList } = await getAuthMenuListApi(params)
      const res = this.convertMenuInformation(authMenuList.data, menuDtoList)
      console.log('转换菜单', res);

      this.authMenuList = res
      return res
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    },
  },
  persist: piniaPersistConfig("geeker-auth", ['currentJobId'])
});
